package org.example.managere.util;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV导入工具类
 */
public class CsvImportUtil {

    /**
     * 从CSV文件导入数据
     * 
     * @param file CSV文件
     * @param targetClass 目标类型
     * @param <T> 目标类型泛型
     * @return 解析后的对象列表
     * @throws IOException 如果读取文件失败
     */
    public static <T> List<T> importFromCsv(MultipartFile file, Class<T> targetClass) throws IOException {
        if (file.isEmpty()) {
            return new ArrayList<>();
        }

        try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(targetClass);

            CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader)
                    .withMappingStrategy(strategy)
                    .withIgnoreLeadingWhiteSpace(true)
                    .withIgnoreEmptyLine(true)
                    .build();

            return csvToBean.parse();
        } catch (Exception e) {
            throw new IOException("解析CSV文件失败: " + e.getMessage(), e);
        }
    }
} 